<template>
  <div class="login">
    <!-- 顶部 -->
    <van-nav-bar right-text="首页" @click-right="gohome('Home')">
      <template #left>
        <div class="nav-left">
          <div class="logo">
            <img src="@/assets/images/home_active.png" alt="">
          </div>
        </div>
        <div class="logo-text">Luckin Coffee</div>
      </template>
    </van-nav-bar>
    <div class="user-box">
      <div class="welcome">忘记密码！</div>
      <div class="welcome-en">forgot password!</div>
      <!-- 填写手机号和密码 -->

      <div class="form-box">
        <!--  @submit="login" -->
        <van-form @submit="commit">
          <van-cell-group inset>
            <van-field v-model="userInfo.phone" name="手机号" label="手机号" placeholder="手机号" :rules="rules.phone" />

            <van-field v-model="userInfo.password" :type="isRegisterPassword?'password':'text'" :right-icon="isRegisterPassword?'closed-eye':'eye-o'" name="新密码" label="新密码" placeholder="新密码（6-16位）" :rules="rules.password" @click-right-icon="toggleRegisterPasswordType" />

            <van-field v-model="userInfo.email" name="邮箱" label="邮箱" placeholder="邮箱" :rules="rules.email" />

            <van-field v-model="userInfo.code" name="邮箱验证码" label="邮箱验证码" placeholder="邮箱验证码" :rules="rules.code">
              <template #button>
                <van-button size="small" color="#1A73E8" :disabled="isSend" @click="getValidCode">{{text}}</van-button>
              </template>
            </van-field>

            <div class="forgot fr">
              <span @click="goState('Login')">已有账号，立即登录</span>
            </div>

          </van-cell-group>

          <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit" color="RGB(12, 52, 186)">
              提交
            </van-button>
          </div>
        </van-form>
      </div>

    </div>

  </div>
</template>

<script>
import '@/assets/less/login.less'
import request from '@/utils/reques'
import qs from 'qs'
//导入表单验证模块
import { validForm } from '@/assets/js/validForm'
export default {
  name: 'Forgot',
  data() {
    return {
      text: '发送验证码',
      // 用户登录信息
      userInfo: {
        phone: '',
        password: '',
        email: '',
        code: ''
      },

      // 表单的校验规则对象
      rules: {
        // 手机号的校验规则
        phone: [{ required: true, message: '手机号格式不正确', trigger: 'onBlur', pattern: /^1\d{10}$/ }],
        // 密码的校验规则
        password: [{ required: true, message: '密码支持数字字母下划线组合，且必须以字母开头，6-16位', trigger: 'onBlur', pattern: /^[A-za-z]\w{5,15}$/ }],
        // 昵称的校验规则 pattern: /^\w\u4e00-\u9fa5{1,10}$/
        nickName: [{ required: true, message: '昵称可以由字母、数字、下划线、汉字组成（1-10字符）', trigger: 'onBlur', pattern: /^.{1,10}$/ }],
        // 邮箱的验证规则
        email: [{ required: true, message: '请输入正确格式的邮箱', trigger: 'onBlur', pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/ }],
        // 邮箱验证码的验证规则
        code: [{ required: true, message: '请输入正确的邮箱验证码', trigger: 'onBlur', pattern: /^[A-Za-z\d]{6}$/ }]
      },
      isRegisterPassword: true,
      //是否下一步
      isNext: false,

      //是否发送
      isSend: false
    }
  },
  methods: {
    jumpForgotpage() {
      this.$router.push({ name: 'Forgot' })
    },
    gohome(home) {
      this.$router.push({ name: home })
    },

    //提交
    async commit() {
      //构造表单验证信息
      let o = {
        phone: {
          value: this.userInfo.phone,
          errorMsg: '手机号格式不正确',
          reg: /^1[3-9]\d{9}$/
        },
        password: {
          value: this.userInfo.password,
          errorMsg: '新密码由数字字母下划线组合(6-16字符)',
          reg: /^[A-Za-z]\w{5,15}$/
        }
      }

      let isPass = validForm.valid(o)
      if (isPass) {
        this.$toast.loading({
          message: '加载中...',
          forbidClick: true,
          duration: 0
        })
        try {
          const { data: res } = await request.post(
            '/retrievePassword',
            qs.stringify({
              appkey: this.appkey,
              phone: this.userInfo.phone,
              password: this.userInfo.password
            })
          )

          if (res) {
            this.$toast.clear()

            this.$toast(res.msg)
          } else if (res.code == 'L001') {
            setTimeout(() => {
              this.goState('Login')
            }, 800)
          }
        } catch (error) {
          this.$toast.clear()
        }
      }
    },
    changeIsShow() {
      this.isShow = !this.isShow
    },
    toggleRegisterPasswordType() {
      this.isRegisterPassword = !this.isRegisterPassword
    },
    // 发送验证码
    async getValidCode() {
      //构造表单验证信息
      let o = {
        email: {
          value: this.userInfo.email,
          errorMsg: '邮箱格式不正确',
          reg: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
        }
      }

      let isPass = validForm.valid(o)

      if (!isPass) {
        return
      }

      let time = 60

      this.isSend = true
      this.text = `${time}秒后重新发送`

      let timer = setInterval(() => {
        if (time <= 0) {
          clearInterval(timer)
          timer = null
          time = 60
          this.isSend = false
        } else {
          time--
          this.text = `${time}秒后重新发送`
        }
      }, 1000)

      //发起获取验证码请求
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      })
      try {
        const { data: res } = await request.post(
          '/emailValidCode',
          qs.stringify({
            appkey: this.appkey,
            email: this.userInfo.email
          })
        )

        if (res) {
          this.$toast.clear()

          this.$toast(res.msg)
          // console.log(res)
        }
      } catch (error) {
        this.$toast.clear()
      }
    },
    //跳转页面
    goState(name) {
      this.$router.push({ name })
    }
  }
}
</script>

<style lang="less" scoped>
.forgot {
  margin-top: 10px;
}
</style>